<?php

namespace App\Exceptions;

use App\Services\DingService;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Exception $exception)
    {
        // if (env('DING_SEND', false) == true) {
        //     DingService::getInstance()->textMsgSend('发生异常' . PHP_EOL . $exception->getMessage());
        // }

        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
//        return parent::render($request, $exception);
        // 如果config配置debug为true ==>debug模式的话让laravel自行处理
//        if (config('app.debug')) {
//            return parent::render($request, $exception);
//        }
        return $this->handle($request, $exception);
    }

    /**
     * @param $request
     * @param Exception $exception
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * @throws Exception
     */
    public function handle($request, Exception $exception)
    {
//        return parent::render($request, $exception);

        // 只处理自定义的APIException异常
        if ($exception instanceof ApiException) {
            $result = return_error_msg($exception->getMessage());

        } elseif ($exception instanceof EmptyException) {
            $result = return_error_msg($exception->getMessage());

        } else {
            // 定义异常开关
            if (config('app.debug')) {
                return parent::render($request, $exception);
            }

            $result = return_error_msg('服务器内部错误');
        }
        //todo 记录日志 和 消息通知（邮件短信等）
        Log::error($exception->getMessage());
        return response()->json($result);

    }
}
